import os
import struct
import sys
 
"""解压resource.pak文件
"""

def unpack(outdir, data):
    """Reads a data pack file and returns a dictionary."""
    # Read the header.
    version = struct.unpack('<I', data[:4])[0]
    if version == 4:
        resource_count, encoding = struct.unpack('<IB', data[4:9])
        alias_count = 0
        header_size = 9
    elif version == 5:
        encoding, resource_count, alias_count = struct.unpack(
            '<BxxxHH', data[4:12])
        header_size = 12
    else:
        raise Exception('Found version: ' + str(version))

    print('version      :', version)
    print('encoding     :', encoding)
    print('resource_cout:', resource_count)
    print('alias_count  :', alias_count)

    resources = {}
    kIndexEntrySize = 2 + 4  # Each entry is a uint16 and a uint32.

    def entry_at_index(idx):
        offset = header_size + idx * kIndexEntrySize
        return struct.unpack('<HI', data[offset:offset + kIndexEntrySize])
    prev_resource_id, prev_offset = entry_at_index(0)
    for i in range(1, resource_count + 1):
        resource_id, offset = entry_at_index(i)
        resources[prev_resource_id] = data[prev_offset:offset]

        with open(os.path.join(outdir, str(prev_resource_id)), 'wb') as f:
            f.write(data[prev_offset:offset])

        prev_resource_id, prev_offset = resource_id, offset
    id_table_size = (resource_count + 1) * kIndexEntrySize
    # Read the alias table.
    kAliasEntrySize = 2 + 2  # uint16, uint16

    def alias_at_index(idx):
        offset = header_size + id_table_size + idx * kAliasEntrySize
        return struct.unpack('<HH', data[offset:offset + kAliasEntrySize])
    aliases = {}
    for i in range(alias_count):
        resource_id, index = alias_at_index(i)
        aliased_id = entry_at_index(index)[0]
        aliases[resource_id] = aliased_id
        resources[resource_id] = resources[aliased_id]
    alias_table_size = kAliasEntrySize * alias_count

 
outdir="out"

def main(pakfile):
    with open(pakfile, 'rb') as f:
        data = f.read()
        if not os.path.exists(outdir):
            os.makedirs(outdir)
        unpack(outdir, data)

 
if __name__ == '__main__':
    main(sys.argv[1])

